/**
 * 
 */
package mdb.com.vn.web.beans;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import mdb.com.vn.model.Customer;
import mdb.com.vn.model.SME;
import mdb.com.vn.model.SmeSms;
import mdb.com.vn.services.MDBServices;
import mdb.com.vn.utils.DateUtils;
import mdb.com.vn.utils.TextUtil;
import mdb.com.vn.web.view.SMEDataModel;

/**
 * @author tu.dod
 * 
 */
@ManagedBean(name = "smeBeans")
@ViewScoped
public class SMEBeans implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String createdBy;
	private Date processDate;
	private Date processDateSme;

	private Date lastUpdated;
	private Date nextProcess;

	private StreamedContent file;
	private boolean btnVisible;
	private boolean btnSaveVisible;
	private List<SME> listOfSME;
	private SMEDataModel smeDataModel;
	private SME smeSelected;

	@ManagedProperty("#{mdbServices}")
	private MDBServices mdbServices;

	@PostConstruct
	public void init() {
		listOfSME = new ArrayList<SME>();
		listOfSME = mdbServices.getSMEsByStatus(TextUtil.PROCESSED);
		smeDataModel = new SMEDataModel(listOfSME);
		lastUpdated = mdbServices.getLastUpdatedLoans(TextUtil.SME_MODULE);
		nextProcess = DateUtils.nextMonth(lastUpdated, 1);
	}

	public void searchSMEByDate() {
		if (processDate != null) {
			listOfSME = mdbServices.getSMEByStatusProcessDate(TextUtil.PROCESSED, processDate);
			smeDataModel = new SMEDataModel(listOfSME);
		} else {
			listOfSME = mdbServices.getSMEsByStatus(TextUtil.PROCESSED);
			smeDataModel = new SMEDataModel(listOfSME);
		}
	}
	public void transferDataToSendSMS(){
		try {
			for (SME sme : listOfSME) {
				Customer customer = mdbServices.getCustomerInfos(sme.getGcif());
				String phone = "";
				String branch = "";
				if (customer != null) {
					phone = customer.getPhoneCountryCode() + "-"
							+ customer.getPhoneAreaCode() + "-"
							+ customer.getPhoneNumber();
					branch = customer.getBranchCode();
					
				} else {
					phone = "N/A";
					branch = "Anonymous";
				}
				//String lkd_num_g2 = mdbServices.getAllLuckyDrawG1Code(TextUtil.SME_MODULE,sme.getGcif(),TextUtil.PROCESSED);
				SmeSms smeSms = new SmeSms();
				smeSms.setId(sme.getId());
				smeSms.setCloAvgBal(sme.getCloAvgBal());
				smeSms.setCreatedBy(sme.getCreatedBy());
				smeSms.setFinCycle(sme.getFinCycle());
				smeSms.setGcif(sme.getGcif());
				smeSms.setLkdNum(sme.getLkdNum());
				smeSms.setPeriodCode(sme.getPeriodCode());
				smeSms.setPhoneNum(phone);
				smeSms.setProcessDate(sme.getProcessDate());
				smeSms.setStatus(sme.getStatus());
				smeSms.setBranchCode(branch);
				mdbServices.addSmeSms(smeSms);
			}
			FacesContext
			.getCurrentInstance()
			.addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_INFO,
							"Chuyên dữ liệu thành công cho phép chi nhánh cập nhật số điện thoại",
							""));
			
		} catch (Exception e) {
			FacesContext
			.getCurrentInstance()
			.addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Đã cố xảy ra trong quá trình chuyển dữ liệu",
							"Vui lòng liên hệ quản trị để khác phục sự cố này"));
		}
		
	}
	public void generateLuckyDrawForSME() {
		if (createdBy.equals("TUNG.NS")) {
			mdbServices.addSMELuckyDrawByScript(createdBy, processDateSme);
			listOfSME = mdbServices.getSMEsByStatus(TextUtil.PROCESSED);
			smeDataModel = new SMEDataModel(listOfSME);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_INFO,
							"Đã cấp mã dự thưởng cho khách hàng", ""));
			lastUpdated = mdbServices.getLastUpdatedLoans(TextUtil.SME_MODULE);
			nextProcess = DateUtils.nextMonth(lastUpdated, 1);
		} else {
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Giao dịch bị từ chối do bạn không có quyền",
							"Vui lòng liên hệ quản trị hệ thống"));
		}
	}

	public void createExcelSMEByPoi() {
		Row row = null;
		Cell cell = null;
		try {
			Workbook wb = new HSSFWorkbook();
			HSSFCellStyle styleHeader = (HSSFCellStyle) wb.createCellStyle();
			HSSFFont fontHeader = (HSSFFont) wb.createFont();
			fontHeader.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			styleHeader.setFont(fontHeader);
			Sheet sheet = wb.createSheet("SME");
			row = sheet.createRow((short) 0);
			List<String> columnNames = new ArrayList<String>();

			columnNames.add("Điểm giao dịch");
			columnNames.add("Ngày xử lý");
			columnNames.add("Tên khách hàng");
			columnNames.add("Số CIF");
			columnNames.add("Số điện thoại");
			columnNames.add("Số dư trung bình");
			columnNames.add("Tháng");
			columnNames.add("Phiếu mua hàng (100.000VND)");
			columnNames.add("Tổng số mã dự thưởng");
			columnNames.add("Mã số dự thưởng");
			for (int i = 0; i < columnNames.size(); i++) {
				cell = row.createCell(i);
				cell.setCellValue(columnNames.get(i));
				cell.setCellStyle(styleHeader);
			}
			int j = 1;
			List<Object[]> tabularData = new ArrayList<Object[]>();
			for (SME sme : listOfSME) {
				Customer customer = mdbServices.getCustomerInfos(sme.getGcif());
				String phone = "";
				String companyName = "";
				String customerName = "";
				if (customer != null) {
					phone = customer.getPhoneCountryCode()+customer.getPhoneAreaCode()+customer.getPhoneNumber();
					customerName = customer.getCustomerName();
					companyName = mdbServices.getCompanyNameByCode(customer.getBranchCode());
					if (companyName == null || companyName.equals("")) {
						companyName = "N/A";
					}
					
				} else {
					phone = "N/A";
				}
				String lkd_num_g2 = mdbServices.getAllLuckyDrawG1Code(TextUtil.SME_MODULE,sme.getGcif(),TextUtil.PROCESSED);
				
				tabularData.add(new Object[] {
						companyName,
						DateUtils.format(sme.getProcessDate(), "dd/MM/yyyy") ,
						customerName,
						sme.getGcif(),
						phone,
						sme.getCloAvgBal(),
						sme.getPeriodCode() + "/" + sme.getFinCycle(),
						sme.getLkdNum(),
						sme.getLkdNum(),
						lkd_num_g2});
			}
			HSSFCellStyle styleRow = (HSSFCellStyle) wb.createCellStyle();
			HSSFFont fontRow = (HSSFFont) wb.createFont();
			fontRow.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
			styleRow.setFont(fontRow);

			for (Object[] temp : tabularData) {
				row = sheet.createRow((short) j);
				for (int k = 0; k < temp.length; k++) {
					cell = row.createCell(k);
					cell.setCellValue(temp[k].toString());
					cell.setCellStyle(styleRow);
				}
				j++;
			}
			String excelFileName = "SME_REPORT.xls";
			FileOutputStream fos = new FileOutputStream(excelFileName);
			wb.write(fos);
			fos.flush();
			fos.close();
			InputStream stream = new BufferedInputStream(new FileInputStream(
					excelFileName));
			file = new DefaultStreamedContent(stream, "application/xls",
					excelFileName);
			setBtnVisible(true);
			FacesContext
					.getCurrentInstance()
					.addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_INFO,
									"Xử lý xuất dữ liệu thành công",
									"Vui lòng nhấn nút 'Tải về máy' để tại file excell về máy."));
		} catch (Exception e) {
			setBtnVisible(false);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Xử lý xuất dữ liệu thất bại",
							"Vui lòng liên hệ quản trị hệ thống."));
			e.printStackTrace();
		}
	}

	public void downloadPreventedSME() {
		file = null;
	}

	/**
	 * @param mdbServices
	 *            the mdbServices to set
	 */
	public void setMdbServices(MDBServices mdbServices) {
		this.mdbServices = mdbServices;
	}

	/**
	 * @return the createdBy
	 */
	public String getCreatedBy() {
		return createdBy;
	}

	/**
	 * @param createdBy
	 *            the createdBy to set
	 */
	public void setCreatedBy(String createdBy) {
		this.createdBy = createdBy;
	}

	/**
	 * @return the processDate
	 */
	public Date getProcessDate() {
		return processDate;
	}

	/**
	 * @param processDate
	 *            the processDate to set
	 */
	public void setProcessDate(Date processDate) {
		this.processDate = processDate;
	}

	/**
	 * @return the btnVisible
	 */
	public boolean isBtnVisible() {
		return btnVisible;
	}

	/**
	 * @param btnVisible
	 *            the btnVisible to set
	 */
	public void setBtnVisible(boolean btnVisible) {
		this.btnVisible = btnVisible;
	}

	/**
	 * @return the btnSaveVisible
	 */
	public boolean isBtnSaveVisible() {
		return btnSaveVisible;
	}

	/**
	 * @param btnSaveVisible
	 *            the btnSaveVisible to set
	 */
	public void setBtnSaveVisible(boolean btnSaveVisible) {
		this.btnSaveVisible = btnSaveVisible;
	}

	/**
	 * @return the listOfSME
	 */
	public List<SME> getListOfSME() {
		return listOfSME;
	}

	/**
	 * @param listOfSME
	 *            the listOfSME to set
	 */
	public void setListOfSME(List<SME> listOfSME) {
		this.listOfSME = listOfSME;
	}

	/**
	 * @return the file
	 */
	public StreamedContent getFile() {
		return file;
	}

	/**
	 * @return the smeDataModel
	 */
	public SMEDataModel getSmeDataModel() {
		return smeDataModel;
	}

	/**
	 * @return the smeSelected
	 */
	public SME getSmeSelected() {
		return smeSelected;
	}

	/**
	 * @param smeSelected
	 *            the smeSelected to set
	 */
	public void setSmeSelected(SME smeSelected) {
		this.smeSelected = smeSelected;
	}

	/**
	 * @return the lastUpdated
	 */
	public Date getLastUpdated() {
		return lastUpdated;
	}

	/**
	 * @param lastUpdated
	 *            the lastUpdated to set
	 */
	public void setLastUpdated(Date lastUpdated) {
		this.lastUpdated = lastUpdated;
	}

	/**
	 * @return the nextProcess
	 */
	public Date getNextProcess() {
		return nextProcess;
	}

	/**
	 * @param nextProcess
	 *            the nextProcess to set
	 */
	public void setNextProcess(Date nextProcess) {
		this.nextProcess = nextProcess;
	}

	/**
	 * @return the processDateSme
	 */
	public Date getProcessDateSme() {
		return processDateSme;
	}

	/**
	 * @param processDateSme the processDateSme to set
	 */
	public void setProcessDateSme(Date processDateSme) {
		this.processDateSme = processDateSme;
	}

}
